<style>
    .form-label {
        transition: all 0.3s ease;
    }
    
    .form-label:hover {
        color: var(--primary-color);
    }
    
    .badge {
        transition: all 0.3s ease;
    }
    
    .badge:hover {
        transform: scale(1.1);
    }
    
    /* 列表项动画 */
    .list-group-item {
        transition: all 0.3s ease;
    }
    
    .list-group-item:hover {
        transform: translateX(5px);
        background: rgba(var(--bs-primary-rgb), 0.1);
    }
    
    /* 按钮动画 */
    .btn {
        transition: all 0.3s ease;
    }
    
    .btn:hover {
        transform: translateY(-2px);
    }
    
    /* 输入框动画 */
    .form-control {
        transition: all 0.3s ease;
    }
    
    .form-control:focus {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
</style>
<label class="form-label">
    <span class="badge badge-info rounded-pill me-2" 
        data-bs-toggle="tooltip" 
        title="{{ key }}">
        <i class="bi bi-info-circle"></i>
    </span>
    {{ config.description }}
</label>
{% if key == 'LISTEN_LIST' %}
    <div class="mb-2">
        <div class="input-group mb-2">
            <input type="text" class="form-control" 
                id="input_{{ key }}" 
                placeholder="请输入要监听的用户">
            <button class="btn btn-primary" type="button" 
                onclick="addNewUser('{{ key }}')"
                title="添加用户">
                <i class="bi bi-plus-lg"></i>
            </button>
        </div>
        <div id="selected_users_{{ key }}" class="list-group">
            {% if config.value %}
                {% for user in config.value %}
                    {% if user %}
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            {{ user }}
                            <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('{{ key }}', '{{ user }}')" title="删除用户">
                                <i class="bi bi-x-lg"></i>
                            </button>
                        </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
        </div>
    </div>
    <input type="text" class="form-control" 
        id="{{ key }}" name="{{ key }}" 
        value="{{ config.value|join(',') }}"
        placeholder="多个值用英文逗号分隔"
        readonly
        style="display: none;">
{% elif key == 'DEEPSEEK_BASE_URL' %}
    <div class="mb-3">
        <select class="form-select mb-2" id="api_provider_select" onchange="updateApiProvider(this.value)" aria-label="选择API提供商">
            <option value="">请选择API提供商</option>
        </select>

        <!-- 添加自定义 API 输入框 -->
        <div id="customApiInput" class="mb-2" style="display: none;">
            <input type="text" class="form-control" 
                   placeholder="请输入自定义 API 地址"
                   onchange="updateCustomApi(this.value)">
        </div>

        <!-- 注册链接容器 -->
        <div id="register_links" class="d-none">
            <!-- 注册链接将通过JavaScript动态添加 -->
        </div>

        <input type="text" class="form-control" 
            id="{{ key }}" name="{{ key }}" 
            value="{{ config.value }}"
            readonly
            style="display: none;">
    </div>

    <script>
    let modelConfigs = null;
    
    // 获取配置数据
    async function fetchModelConfigs() {
        try {
            const response = await fetch('/get_model_configs');
            const data = await response.json();
            modelConfigs = data;
            initializeSelects();
        } catch (error) {
            console.error('获取配置失败:', error);
        }
    }

    // 初始化选择框
    function initializeSelects() {
        if (!modelConfigs) return;

        // 初始化API提供商选择框
        const apiSelect = document.getElementById('api_provider_select');
        apiSelect.innerHTML = '<option value="">请选择API提供商</option>';
        
        // 按优先级排序并添加选项
        modelConfigs.api_providers
            .sort((a, b) => a.priority - b.priority)
            .forEach(provider => {
                if (provider.status === 'active') {
                    apiSelect.innerHTML += `<option value="${provider.id}" 
                        data-url="${provider.url}"
                        data-register="${provider.register_url}"
                        >${provider.name}</option>`;
                }
            });

        // 根据当前配置设置初始值
        const currentUrl = document.getElementById('DEEPSEEK_BASE_URL').value;
        const currentProvider = modelConfigs.api_providers.find(p => p.url === currentUrl);
        
        if (currentProvider) {
            apiSelect.value = currentProvider.id;
            updateApiProvider(currentProvider.id);
        } else if (currentUrl) {
            apiSelect.value = 'custom';
            showCustomApiInput(currentUrl);
        }
    }

    // 显示自定义API输入框
    function showCustomApiInput(value = '') {
        const customApiInput = document.getElementById('customApiInput');
        customApiInput.style.display = 'block';
        if (value) {
            customApiInput.querySelector('input').value = value;
        }
    }

    // 更新API提供商
    function updateApiProvider(value) {
        const baseUrlInput = document.getElementById('DEEPSEEK_BASE_URL');
        const customApiInput = document.getElementById('customApiInput');
        const registerLinks = document.getElementById('register_links');
        const modelSelect = document.getElementById('model_select');

        // 重置所有状态
        customApiInput.style.display = 'none';
        registerLinks.classList.add('d-none');
        registerLinks.innerHTML = '';

        // 处理自定义选项
        if (value === 'custom') {
            showCustomApiInput();
            updateModelSelect('custom');
            return;
        }

        // 处理未选择情况
        if (!value) {
            updateModelSelect('');
            return;
        }

        // 获取选中的提供商配置
        const selectedOption = document.querySelector(`#api_provider_select option[value="${value}"]`);
        if (!selectedOption) return;

        // 更新API URL
        const apiUrl = selectedOption.dataset.url;
        baseUrlInput.value = apiUrl;
        
        // 添加标记是否为 Ollama
        if (value === 'ollama') {
            baseUrlInput.dataset.isOllama = 'true';
        } else {
            baseUrlInput.dataset.isOllama = 'false';
        }

        // 创建注册按钮
        const registerUrl = selectedOption.dataset.register;
        if (registerUrl) {
            const link = document.createElement('a');
            link.href = registerUrl;
            link.className = 'btn btn-outline-primary w-100';
            link.target = '_blank';
            link.innerHTML = `<i class="bi bi-box-arrow-up-right me-1"></i>前往${selectedOption.textContent.replace(' API', '')}注册`;
            registerLinks.innerHTML = '';
            registerLinks.appendChild(link);
            registerLinks.classList.remove('d-none');
        }

        // 更新模型选择框
        updateModelSelect(value);
    }

    // 更新模型选择框
    async function updateModelSelect(providerId) {
        const modelSelect = document.getElementById('model_select');
        modelSelect.innerHTML = '<option value="">请选择模型</option>';

        if (providerId === 'custom') {
            modelSelect.innerHTML += '<option value="custom">自定义模型</option>';
            return;
        }

        if (!providerId) return;

        // 如果是 Ollama，尝试获取本地模型列表
        if (providerId === 'ollama') {
            try {
                const response = await fetch('http://localhost:11434/api/tags');
                if (response.ok) {
                    const data = await response.json();
                    const ollamaModels = data.models || [];
                    ollamaModels.forEach(model => {
                        modelSelect.innerHTML += `
                            <option value="${model.name}" 
                                data-type="chat"
                                data-context-length="16000"
                                >${model.name}</option>`;
                    });
                }
            } catch (error) {
                console.error('获取Ollama模型列表失败:', error);
                // 如果获取失败，使用配置文件中的默认模型
                const defaultModels = modelConfigs.models[providerId] || [];
                defaultModels.forEach(model => {
                    if (model.status === 'active') {
                        modelSelect.innerHTML += `
                            <option value="${model.id}" 
                                data-type="${model.type}"
                                data-context-length="${model.context_length}"
                                >${model.name}</option>`;
                    }
                });
            }
        } else {
            // 其他提供商使用配置文件中的模型列表
            const providerModels = modelConfigs.models[providerId] || [];
            providerModels.forEach(model => {
                if (model.status === 'active') {
                    modelSelect.innerHTML += `
                        <option value="${model.id}" 
                            data-type="${model.type}"
                            data-context-length="${model.context_length}"
                            >${model.name}</option>`;
                }
            });
        }

        // 添加自定义选项
        modelSelect.innerHTML += '<option value="custom">自定义模型</option>';

        // 设置当前选中的模型
        const currentModel = document.getElementById('MODEL').value;
        const allModels = providerId === 'ollama' ? 
            (modelSelect.querySelectorAll('option') || []) : 
            (modelConfigs.models[providerId] || []);
        
        if (Array.from(allModels).some(m => m.value === currentModel || m.id === currentModel)) {
            modelSelect.value = currentModel;
        } else if (currentModel) {
            modelSelect.value = 'custom';
            document.getElementById('customModelInput').style.display = 'block';
            document.getElementById('customModelInput').querySelector('input').value = currentModel;
        }
    }

    // 更新自定义API
    function updateCustomApi(value) {
        document.getElementById('DEEPSEEK_BASE_URL').value = value;
    }

    // 更新模型
    function updateModel(value) {
        const modelInput = document.getElementById('MODEL');
        const customModelInput = document.getElementById('customModelInput');
        
        if (value === 'custom') {
            customModelInput.style.display = 'block';
        } else {
            customModelInput.style.display = 'none';
            modelInput.value = value;
        }
    }

    // 更新自定义模型
    function updateCustomModel(value) {
        document.getElementById('MODEL').value = value;
    }

    // 页面加载时获取配置
    document.addEventListener('DOMContentLoaded', fetchModelConfigs);
    </script>
{% elif key == 'PROMPT_ENHANCEMENT' %}
    <select class="form-select" id="{{ key }}" name="{{ key }}">
        <option value="True" {% if config.value %}selected{% endif %}>启用</option>
        <option value="False" {% if not config.value %}selected{% endif %}>停用</option>
    </select>
{% elif key == 'AVATAR_DIR' %}
    <select class="form-select" id="{{ key }}" name="{{ key }}">
        {% for option in config.options %}
        <option value="{{ option }}" {% if option == config.value %}selected{% endif %}>
            {{ option.split('/')[-1] }}
        </option>
        {% endfor %}
    </select>
{% elif config.value is boolean %}
    <div class="form-check form-switch d-flex align-items-center" style="padding: 6px 0; min-height: 38px;">
        <input class="form-check-input me-2" type="checkbox" role="switch" 
            id="{{ key }}" name="{{ key }}" 
            {% if config.value %}checked{% endif %}
            style="margin: 0;">
        <label class="form-check-label mb-0" for="{{ key }}" style="line-height: 24px;">
            {{ '启用' if config.value else '停用' }}
        </label>
    </div>
{% elif key == 'MODEL' %}
    <div class="mb-3">
        <select class="form-select mb-2" id="model_select" onchange="updateModel(this.value)" aria-label="选择模型">
            <option value="">请选择模型</option>
        </select>

        <!-- 添加自定义模型输入框 -->
        <div id="customModelInput" class="mb-2" style="display: none;">
            <input type="text" class="form-control" 
                   placeholder="请输入自定义模型名称"
                   onchange="updateCustomModel(this.value)"
                   value="{{ config.value if not config.value in ['deepseek-ai/DeepSeek-V3', 'deepseek-ai/DeepSeek-R1', 'Pro/deepseek-ai/DeepSeek-V3', 'Pro/deepseek-ai/DeepSeek-R1', 'deepseek-chat', 'deepseek-reasoner'] else '' }}">
        </div>

        <input type="text" class="form-control" 
            id="{{ key }}" name="{{ key }}" 
            value="{{ config.value }}"
            readonly
            style="display: none;">
    </div>
{% elif config.type == "number" %}
    {% if key == 'MAX_TOKEN' %}
        <style>
            .token-slider {
                -webkit-appearance: none;
                appearance: none;
                width: 100%;
                height: 8px;
                border-radius: 4px;
                background: #e2e8f0;
                outline: none;
                transition: all 0.3s ease;
            }
            
            .token-slider::-webkit-slider-thumb {
                -webkit-appearance: none;
                appearance: none;
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: #fff;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 0 4px rgba(0,0,0,0.2);
                border: 2px solid #0d6efd;
            }
            
            .token-slider::-moz-range-track {
                background: #e2e8f0;
                height: 8px;
                border-radius: 4px;
            }
            
            .token-slider::-moz-range-thumb {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: #fff;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 0 4px rgba(0,0,0,0.2);
                border: 2px solid #0d6efd;
            }
            
            .token-slider::-webkit-slider-thumb:hover {
                background: #f8f9fa;
                box-shadow: 0 0 8px rgba(13,110,253,0.5);
                transform: scale(1.1);
            }
            
            .token-slider:active {
                opacity: 0.8;
            }
            
            .token-value {
                transition: all 0.2s ease;
            }
            .token-value.updating {
                color: #0d6efd;
                transform: scale(1.1);
            }
        </style>
        
        <div class="mb-3">
            <div class="d-flex justify-content-between align-items-center">
                <span>当前值: <strong id="{{ key }}_display" class="token-value">{{ config.value }}</strong></span>
            </div>
            <input type="range" 
                class="token-slider" 
                id="{{ key }}_slider" 
                min="50"
                max="5000"
                step="5"
                value="{{ config.value }}"
                oninput="updateToken('{{ key }}', this.value)"
                style="cursor: pointer;"
                title="最大token数滑动条">
            <div class="d-flex justify-content-between" style="color: #6c757d; font-size: 0.875rem;">
                <span>50</span>
                <span>5000</span>
            </div>
            <!-- 隐藏的实际提交值输入框 -->
            <input type="hidden" 
                id="{{ key }}" 
                name="{{ key }}" 
                value="{{ config.value }}">
        </div>

        <script>
            function updateToken(key, value) {
                // 将字符串转换为整数
                const numValue = parseInt(value);
                
                // 更新显示值
                const displayElement = document.getElementById(key + '_display');
                if (displayElement) {
                    displayElement.classList.add('updating');
                    displayElement.textContent = numValue;
                    setTimeout(() => {
                        displayElement.classList.remove('updating');
                    }, 300);
                }
                
                // 更新隐藏的实际提交值
                const inputElement = document.getElementById(key);
                if (inputElement) {
                    inputElement.value = numValue;
                }
            }
        </script>
    {% elif key == 'TEMPERATURE' %}
        <style>
            .temperature-slider {
                -webkit-appearance: none;
                appearance: none;
                width: 100%;
                height: 8px;
                border-radius: 4px;
                background: linear-gradient(to right, 
                    #3498db 0%,
                    #3498db 60%,
                    #9b59b6 70%,
                    #e74c3c 80%,
                    #e74c3c 100%
                );
                outline: none;
                transition: all 0.3s ease;
            }
            
            .temperature-slider::-webkit-slider-thumb {
                -webkit-appearance: none;
                appearance: none;
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: #fff;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 0 4px rgba(0,0,0,0.2);
                border: 2px solid #0d6efd;
            }
            
            .temperature-slider::-moz-range-thumb {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: #fff;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 0 4px rgba(0,0,0,0.2);
                border: 2px solid #0d6efd;
            }
            
            .temperature-value {
                transition: all 0.2s ease;
            }
            .temperature-value.updating {
                color: #0d6efd;
                transform: scale(1.1);
            }
            
            .slider-labels {
                color: #6c757d;
                font-size: 0.875rem;
            }
            .slider-labels .low {
                color: #3498db;
            }
            .slider-labels .high {
                color: #e74c3c;
            }
        </style>
        
        <div class="mb-3">
            <div class="d-flex justify-content-between align-items-center">
                <span>当前值: <strong id="{{ key }}_display" class="temperature-value">{{ config.value }}</strong></span>
            </div>
            <input type="range" 
                class="temperature-slider" 
                id="{{ key }}_slider" 
                min="0.00"
                max="1.70"
                step="0.01"
                value="{{ config.value }}"
                oninput="updateTemperature('{{ key }}', this.value)"
                style="cursor: pointer;"
                title="温度参数滑动条">
            <div class="d-flex justify-content-between slider-labels">
                <span class="low">0.0</span>
                <span class="high">1.7</span>
            </div>
            <!-- 隐藏的实际提交值输入框 -->
            <input type="hidden" 
                id="{{ key }}" 
                name="{{ key }}" 
                value="{{ config.value }}">
        </div>

        <script>
            function updateTemperature(key, value) {
                // 将字符串转换为数字
                const numValue = parseFloat(value);
                
                // 更新显示值
                const displayElement = document.getElementById(key + '_display');
                if (displayElement) {
                    displayElement.classList.add('updating');
                    displayElement.textContent = numValue;
                    setTimeout(() => {
                        displayElement.classList.remove('updating');
                    }, 300);
                }
                
                // 更新隐藏的实际提交值
                const inputElement = document.getElementById(key);
                if (inputElement) {
                    inputElement.value = numValue;
                    // 触发 change 事件以确保表单能捕获到值的变化
                    const event = new Event('change', { bubbles: true });
                    inputElement.dispatchEvent(event);
                }

                // 调试输出
                console.log(`Temperature updated - key: ${key}, value: ${numValue}, type: ${typeof numValue}`);
                console.log(`Hidden input value: ${document.getElementById(key).value}`);
            }

            // 确保页面加载时初始化温度值
            document.addEventListener('DOMContentLoaded', function() {
                const slider = document.getElementById('{{ key }}_slider');
                if (slider) {
                    updateTemperature('{{ key }}', slider.value);
                }
            });
        </script>
    {% else %}
        <input type="number" 
            class="form-control" 
            id="{{ key }}" 
            name="{{ key }}" 
            value="{{ config.value }}"
            step="0.1"
            {% if config.min is defined %}min="{{ config.min }}"{% endif %}
            {% if config.max is defined %}max="{{ config.max }}"{% endif %}>
    {% endif %}
{% elif key == 'MOONSHOT_API_KEY' %}
    <div class="mb-3">
        <input type="text" class="form-control mb-2" 
            id="{{ key }}" name="{{ key }}" 
            value="{{ config.value }}"
            placeholder="请输入 Moonshot API 密钥">
        <a href="https://platform.moonshot.cn/console/api-keys" 
            class="btn btn-primary w-100"
            target="_blank"
            rel="noopener">
            <i class="bi bi-box-arrow-up-right me-1"></i>点我注册
        </a>
    </div>
{% elif key == 'QUIET_TIME_START' or key == 'QUIET_TIME_END' %}
    <div class="mb-3">
        <div class="time-picker-container-{{ key }}">
            <input type="text" 
                class="form-control time-display" 
                id="{{ key }}_display" 
                value="{{ config.value }}"
                readonly
                placeholder="请选择时间"
                onclick="showTimePicker_{{ key }}()">
            <input type="hidden" 
                id="{{ key }}" 
                name="{{ key }}" 
                value="{{ config.value }}">
            
            <!-- 时间选择器弹出层 -->
            <div class="time-picker-dropdown-{{ key }}" id="time_picker_{{ key }}" style="display: none;">
                <div class="time-header-{{ key }}">
                    {{ config.value }}
                </div>
                <div class="time-columns-container-{{ key }}">
                    <div class="time-column-label-{{ key }}">{{ '开始时间' if key == 'QUIET_TIME_START' else '结束时间' }}</div>
                    <div class="time-columns-{{ key }}">
                        <div class="time-column-{{ key }}">
                            {% for h in range(24) %}
                            <div class="time-option-{{ key }}" data-value="{{ '%02d' % h }}" onclick="selectTimeOption_{{ key }}('hour', '{{ '%02d' % h }}')">{{ '%02d' % h }}</div>
                            {% endfor %}
                        </div>
                        <div class="time-column-{{ key }}">
                            {% for m in range(0, 60, 1) %}
                            <div class="time-option-{{ key }}" data-value="{{ '%02d' % m }}" onclick="selectTimeOption_{{ key }}('minute', '{{ '%02d' % m }}')">{{ '%02d' % m }}</div>
                            {% endfor %}
                        </div>
                    </div>
                </div>
                
                <div class="time-picker-footer-{{ key }}">
                    <button type="button" class="btn btn-secondary" onclick="cancelTimePicker_{{ key }}()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="confirmTimePicker_{{ key }}()">确定</button>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        /* 为每个时间选择器创建独立的样式命名空间 */
        .time-picker-container-{{ key }} {
            position: relative;
            width: 100%;
        }
        
        .time-display {
            cursor: pointer;
        }
        
        .time-picker-dropdown-{{ key }} {
            position: absolute;
            z-index: 1050;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
            width: 300px;
            overflow: hidden;
        }
        
        [data-bs-theme="dark"] .time-picker-dropdown-{{ key }} {
            background-color: #2b3035;
            border: 1px solid #444;
        }
        
        .time-header-{{ key }} {
            padding: 12px 16px;
            text-align: center;
            border-bottom: 1px solid #eee;
            font-weight: 500;
        }
        
        [data-bs-theme="dark"] .time-header-{{ key }} {
            border-bottom: 1px solid #444;
        }
        
        .time-columns-container-{{ key }} {
            padding: 16px;
        }
        
        .time-column-label-{{ key }} {
            text-align: center;
            font-weight: 500;
            margin-bottom: 12px;
            font-size: 16px;
        }
        
        .time-columns-{{ key }} {
            display: flex;
            height: 200px;
            overflow: hidden;
        }
        
        .time-column-{{ key }} {
            flex: 1;
            overflow-y: auto;
            text-align: center;
            scrollbar-width: thin;
            padding: 0 4px;
        }
        
        .time-column-{{ key }}::-webkit-scrollbar {
            width: 4px;
        }
        
        .time-column-{{ key }}::-webkit-scrollbar-thumb {
            background-color: #ccc;
            border-radius: 4px;
        }
        
        [data-bs-theme="dark"] .time-column-{{ key }}::-webkit-scrollbar-thumb {
            background-color: #666;
        }
        
        .time-option-{{ key }} {
            padding: 8px 0;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 15px;
            border-radius: 4px;
            margin: 2px 0;
        }
        
        .time-option-{{ key }}:hover {
            background-color: #f0f7ff;
        }
        
        [data-bs-theme="dark"] .time-option-{{ key }}:hover {
            background-color: #3a4046;
        }
        
        .time-option-{{ key }}.selected {
            background-color: #e6f0ff;
            color: #0d6efd;
            font-weight: 500;
        }
        
        [data-bs-theme="dark"] .time-option-{{ key }}.selected {
            background-color: #0d6efd;
            color: white;
        }
        
        .time-picker-footer-{{ key }} {
            display: flex;
            justify-content: flex-end;
            padding: 10px 16px;
            border-top: 1px solid #eee;
            gap: 8px;
        }
        
        [data-bs-theme="dark"] .time-picker-footer-{{ key }} {
            border-top: 1px solid #444;
        }
    </style>
    
    <script>
        // 修改时间选择器的变量和函数
        let timeSelection_{{ key }} = {
            hour: '{{ config.value.split(":")[0] if ":" in config.value else "00" }}',
            minute: '{{ config.value.split(":")[1] if ":" in config.value and config.value.split(":")|length > 1 else "00" }}'
        };
        
        // 显示时间选择器
        function showTimePicker_{{ key }}() {
            const picker = document.getElementById('time_picker_{{ key }}');
            const input = document.getElementById('{{ key }}_display');
            
            // 计算位置
            const inputRect = input.getBoundingClientRect();
            const viewportHeight = window.innerHeight;
            const spaceBelow = viewportHeight - inputRect.bottom;
            const pickerHeight = 320; // 估计的选择器高度
            
            // 重置位置样式
            picker.style.top = '';
            picker.style.bottom = '';
            picker.style.left = '0';
            
            if (spaceBelow < pickerHeight && inputRect.top > pickerHeight) {
                // 如果下方空间不足且上方空间足够，则在上方显示
                picker.style.bottom = input.offsetHeight + 'px';
            } else {
                // 否则在下方显示
                picker.style.top = input.offsetHeight + 'px';
            }
            
            // 显示选择器
            picker.style.display = 'block';
            
            // 获取当前值
            const currentValue = document.getElementById('{{ key }}').value;
            
            // 初始化选择状态
            if (currentValue) {
                const parts = currentValue.split(':');
                timeSelection_{{ key }}.hour = parts[0] || '00';
                timeSelection_{{ key }}.minute = parts[1] || '00';
                
                // 高亮当前选中的选项
                highlightSelectedTime_{{ key }}();
                
                // 滚动到选中位置
                scrollToSelected_{{ key }}();
            }
        }
        
        // 选择时间选项
        function selectTimeOption_{{ key }}(type, value) {
            // 更新选择
            timeSelection_{{ key }}[type] = value;
            
            // 高亮选中项
            highlightSelectedTime_{{ key }}();
            
            // 更新显示的时间
            updateTimeDisplay_{{ key }}();
        }
        
        // 更新时间显示
        function updateTimeDisplay_{{ key }}() {
            const timeString = `${timeSelection_{{ key }}.hour}:${timeSelection_{{ key }}.minute}`;
            document.querySelector('.time-header-{{ key }}').textContent = 
                timeString;
        }
        
        // 高亮选中的时间
        function highlightSelectedTime_{{ key }}() {
            const columns = document.querySelectorAll('.time-column-{{ key }}');
            
            // 移除所有高亮
            document.querySelectorAll('.time-option-{{ key }}').forEach(option => {
                option.classList.remove('selected');
            });
            
            // 添加高亮
            if (columns[0]) {
                const hourOption = columns[0].querySelector(`.time-option-{{ key }}[data-value="${timeSelection_{{ key }}.hour}"]`);
                if (hourOption) hourOption.classList.add('selected');
            }
            
            if (columns[1]) {
                const minuteOption = columns[1].querySelector(`.time-option-{{ key }}[data-value="${timeSelection_{{ key }}.minute}"]`);
                if (minuteOption) minuteOption.classList.add('selected');
            }
        }
        
        // 滚动到选中位置
        function scrollToSelected_{{ key }}() {
            const columns = document.querySelectorAll('.time-column-{{ key }}');
            
            if (columns[0]) {
                const hourOption = columns[0].querySelector(`.time-option-{{ key }}[data-value="${timeSelection_{{ key }}.hour}"]`);
                if (hourOption) {
                    columns[0].scrollTop = hourOption.offsetTop - columns[0].offsetHeight / 2 + hourOption.offsetHeight / 2;
                }
            }
            
            if (columns[1]) {
                const minuteOption = columns[1].querySelector(`.time-option-{{ key }}[data-value="${timeSelection_{{ key }}.minute}"]`);
                if (minuteOption) {
                    columns[1].scrollTop = minuteOption.offsetTop - columns[1].offsetHeight / 2 + minuteOption.offsetHeight / 2;
                }
            }
        }
        
        // 确认时间选择
        function confirmTimePicker_{{ key }}() {
            const timeString = `${timeSelection_{{ key }}.hour}:${timeSelection_{{ key }}.minute}`;
            
            // 更新输入框和隐藏字段
            document.getElementById('{{ key }}_display').value = timeString;
            document.getElementById('{{ key }}').value = timeString;
            
            // 隐藏选择器
            document.getElementById('time_picker_{{ key }}').style.display = 'none';
        }
        
        // 取消时间选择
        function cancelTimePicker_{{ key }}() {
            document.getElementById('time_picker_{{ key }}').style.display = 'none';
        }
        
        // 点击外部关闭时间选择器
        document.addEventListener('click', function(event) {
            const container = document.querySelector('.time-picker-container-{{ key }}');
            const picker = document.getElementById('time_picker_{{ key }}');
            
            if (container && picker && !container.contains(event.target)) {
                picker.style.display = 'none';
            }
        });
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化时间显示
            updateTimeDisplay_{{ key }}();
        });
    </script>
{% else %}
    <input type="text" class="form-control" 
        id="{{ key }}" name="{{ key }}" 
        value="{{ config.value }}">
{% endif %}

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 检查 localStorage 中的状态
        const darkMode = localStorage.getItem('darkMode');
        if (darkMode === 'enabled') {
            document.body.setAttribute('data-bs-theme', 'dark');
            document.getElementById('darkModeToggle').checked = true; // 更新按钮状态
        }

        // 护眼模式切换
        document.getElementById('darkModeToggle').addEventListener('change', function() {
            if (this.checked) {
                document.body.setAttribute('data-bs-theme', 'dark');
                localStorage.setItem('darkMode', 'enabled'); // 存储状态
            } else {
                document.body.removeAttribute('data-bs-theme');
                localStorage.setItem('darkMode', 'disabled'); // 存储状态
            }
        });
    });
</script> 